<?php 

class Event_CallCenter2PostSelect extends Crud_Event_Handler 
{
	protected $_type = 'postSelect';
	
	/**
	 * Run handler with options array.
	 * 
	 * @param Db_Select $row
	 * @return void
	 */
	public function run($select)
	{
		//$this->_hidePaidCard($select);
		$dt_from = $this->_getParam('date_from');
		$dt_to = $this->_getParam('date_to');
		$search = $this->_getParam('asearch', array());

		$filled = array();
		foreach ($search as $name => $value) {
			if ($value == '') continue;
			$filled[$name] = $value;
		}
		
		$deliveryVarchars = array('city', 'street', 'corps', 'home', 'porch', 'level', 'flat', 'email');
		$deliveryForeign = array('metro' => 'metro_id');
		$deliveryProcess = 0;
		foreach ($deliveryVarchars as $deliveryColumn) {
			if (in_array($deliveryColumn, array_keys($filled))) {
				$deliveryProcess = 1;
			}
		}
		
		foreach ($deliveryForeign as $deliveryColumn) {
			if (in_array($deliveryColumn, array_keys($filled))) {
				$deliveryProcess = 1;
			}
		}
		
		if ($deliveryProcess) {
			$select->join('delivery', 'delivery.id = orders.delivery_id', array());	
			
			foreach ($deliveryVarchars as $deliveryColumn) {
				if (!isset($filled[$deliveryColumn])) continue;
				$value = addslashes($filled[$deliveryColumn]);
				$select->where("delivery.$deliveryColumn like '%{$value}%'");
			}
			
			foreach ($deliveryForeign as $table => $deliveryColumn) {
				if (!isset($filled[$deliveryColumn])) continue;
				
				$select->join($table, "$table.id = delivery.$deliveryColumn", array());
				$value = addslashes($filled[$deliveryColumn]);
				$select->where("$table.name like '%$value%'");
			}
		}
		
		if (isset($filled['admin_user_id'])) {
			$select->join('admin_user', 'admin_user.id = orders.admin_user_id', array());
			$value = addslashes($filled['admin_user_id']);
			$select->where("admin_user.name like '%$value%'");
		}

		$start = substr($dt_from, 0, 10);
		$end = substr($dt_to, 0, 10);
		if(isset($dt_from) && isset($dt_to) && $start == $end){
			$select->where('`orders`.created_at like "'.$dt_from.'%"');
		}else{
		
			if(isset($dt_from))
				$select->where('`orders`.created_at>="'.$dt_from.'"');
			if(isset($dt_to))
				$select->where('`orders`.created_at<="'.$dt_to.'"');
		}
			
		$dateFilter = new Filter_StringToTime();
		if (isset($filled['executed_at_from'])) {
			$value = $dateFilter->filter($filled['executed_at_from']);
			if ($value) {
				$value = date('Y-m-d', $value);
				$select->where('executed_at >= ?', $value);
			}
		}
		
		if (isset($filled['executed_at_to'])) {
			$value = $dateFilter->filter($filled['executed_at_to']);
			if ($value) {
				$value = strtotime("+1 day", $value);
				$value = date('Y-m-d', $value);
				$select->where('executed_at < ?', $value);
			}
		}
		
		if (isset($filled['accepted_at_from'])) {
			$value = $dateFilter->filter($filled['accepted_at_from']);
			if ($value) {
				$value = date('Y-m-d', $value);
				$select->where('accepted_at >= ?', $value);
			}
		}
		
		if (isset($filled['accepted_at_to'])) {
			$value = $dateFilter->filter($filled['accepted_at_to']);
			if ($value) {
				$value = strtotime("+1 day", $value);
				$value = date('Y-m-d', $value);
				$select->where('accepted_at < ?', $value);
			}
		}
		
		if (isset($filled['product'])) {
			$select->join('order2product', 'order2product.order_id = orders.id', array());
			$select->join('product', 'order2product.product_id = product.id', array());
			$value = addslashes($filled['product']);
			$select->where("product.name like '%$value%'");
		}
		$select->reset('order');
		$select->order('`orders`.`created_at` desc');
		$this->_report($select);
	}
	
	/**
	 * Не показывать в колл-центре заказы со статусом "ожидание оплаты картой".
	 * 
	 * @param Db_Select $select
	 * @return void
	 * 
	 */
	protected function _hidePaidCard($select)
	{
		$status = OrderStatusPeer::getInstance()->fetchByKey(OrdersService::STATUS_ORDER_WATING_PAID_CARD);
		$select->where(OrdersPeer::ORDER_STATUS_ID . Db_Select::SQL_NOT_EQUAL, $status->getId());
	}
	
	/**
	 * Создает отчет по выбранным заказам. 
	 * Отдает файл csv и прерывает дальнейшее выполнение скрипта.
	 * 
	 * @param Db_Select $select
	 * @return void
	 */
	protected function _report($select)
	{
		$columns = $this->_getParam('report', array());
		if (!$columns || !$this->_getParam('create_report')) {
			return;
		}
		
		$deliveryColumns = array(
			'firstName',
			'lastName',
			'email',
			'phone',
			'city',
			'street', 
			'home', 
			'corps',
			'porch', 
			'level', 
			'flat',
			'inMkad'
		);
		
		$orderColumns = array(
			'id',
			'deliveryComment',
			'createdAt',
			'executedAt',
			'totalCost',
			'wikimart',
			'percent',
		);
		
		$orderFkColumns = array(
			'paymentMethod' => 'getPaymentMethodsRowByPaymentMethodId',
			'operator' => 'getOrderOperatorRowByOperatorId',
			'deliveryTime'  => 'getDeliveryTimesRowByDeliveryTimeId',
			'status' => 'getOrderStatusRowByOrderStatusId'
		);
		
		//получить всевозможные типы цен, с последующей нормализацией
		$discountTypesRowset = OrdersService::getInstance()->getDiscountPriceTypes();
		$discountTypesRowset = OrdersTypeDiscountPeer::getInstance()->normalizeByPreferKey($discountTypesRowset);
		
		$rowset = OrdersPeer::getInstance()->fetchAll($select);
		$report = array();
		/* @var $row OrdersRow */
		foreach ($rowset as $row) {
			$reportRow = array();
			
			//выставление типа скидки
			if (isset($columns['type_discount'])) {
				$reportRow['type_discount'] = '';
				if (isset($discountTypesRowset[$row->getTypeDiscount()])) {
					/* @var $discountTypeRow OrdersTypeDiscountRow */
					$discountTypeRow = $discountTypesRowset[$row->getTypeDiscount()];
					$reportRow['type_discount'] = $discountTypeRow->getName();
				}
			}
			
			if (isset($columns['type_discount_value'])) {
				$reportRow['type_discount_value'] = '';
				if (isset($discountTypesRowset[$row->getTypeDiscount()])) {
					/* @var $discountTypeRow OrdersTypeDiscountRow */
					$discountTypeRow = $discountTypesRowset[$row->getTypeDiscount()];
					switch($discountTypeRow->getKey()) {
						case OrdersService::DISCOUNT_TYPE_PERCENT:
							$reportRow['type_discount_value'] = $row->getPercent();
							break;
					}
				}
			}
			
			// Добавляем в ряд отчета поля из таблицы delivery
			$delivery = $row->getDeliveryRowByDeliveryId();
			foreach ($deliveryColumns as $deliveryColumn) {
				if (!isset($columns[$deliveryColumn])) continue;
				$getter = 'get' . ucfirst($deliveryColumn);
				$value = $delivery->$getter();
				$reportRow[$deliveryColumn] = $value;
			}
			
			// Добавляем в ряд отчета поля из таблицы orders
			foreach ($orderColumns as $orderColumn) {
				if (!isset($columns[$orderColumn])) continue;
				$getter = 'get' . ucfirst($orderColumn);
				$value = $row->$getter();
				$reportRow[$orderColumn] = $value;
			}
			// Добавляем в ряд отчета цену с доставкой
			if (isset($columns['comments'])) {
				//$value = $row->getId() + $row->getDeliveryCost();
				$ordercomment_select = OrderCommentPeer::getInstance()->select()->where('order_id='.$row->getId());
				$ordercomment_row = OrderCommentPeer::getInstance()->fetchAll($ordercomment_select);
				if($ordercomment_row)
					$com = '';
						foreach($ordercomment_row as $com_row){
							if($com == ''){
								$com .= '"'.$com_row->getComment().'"';
							}else{
								$com .= '"::'.$com_row->getComment().'"';
							}
						}
					$reportRow['comments'] = $com;
			}
			
			if (isset($columns['costWithDelivery'])) {
				$value = $row->getTotalCost() + $row->getDeliveryCost();				
				$reportRow['costWithDelivery'] = $value;
			}
			
			
			
			// Добавляем в ряд отчета поля с внешними ссылками из таблицы orders
			foreach ($orderFkColumns as $orderColumn => $getter) {
				if (!isset($columns[$orderColumn])) continue;
				$fkRow = $row->$getter();
				$value = null;
				if ($fkRow) {
					$value = $fkRow->getName();
				}
				
				$reportRow[$orderColumn] = $value;
			}
			
			// Добавляем в ряд отчета информацию о том, зарегестрировал ли пользователь
			if (isset($columns['isRegistered'])) {
				$registered = 'Нет';
	        	$profile = $row->getProfileRowByProfileId();
	        	if ($profile) {
	        		$email = $profile->getEmail();
	        		if ($email != 'h@detmir.ru') {
	        			$registered = 'Да';
	        		}
	        	}
	        	$reportRow['isRegistered'] = $registered;
			}
			
			$productsInReport = false;
			// Добавляем в ряд отчета поля с информацией о составе заказа
			if (isset($columns['productId']) || isset($columns['productName']) || isset($columns['productCount']) || isset($columns['productPrice'])) {
				$productsInReport = true;
				
				$o2pRowset = $row->getOrder2productRowsetByOrderId();
				if ($o2pRowset->count()) {
					$first = 1;
					foreach ($o2pRowset as $o2p) {
						$productReportRow = $reportRow;
						if (!$first) {
							if (isset($productReportRow['totalCost'])) {
								$productReportRow['totalCost'] = null;
							}
							
							if (isset($productReportRow['costWithDelivery'])) {
								$productReportRow['costWithDelivery'] = null;
							}
						}
						$first = 0;
						
						$product = $o2p->getProductRowByProductId();
						if (isset($columns['productId'])) {
							$productReportRow['productId'] = $product->getInternalId();
						}
						
						if (isset($columns['productName'])) {
							$productReportRow['productName'] = $product->getName();
						}
						
						if (isset($columns['productCount'])) {
							$productReportRow['productCount'] = $o2p->getCount();
						}
						
						if (isset($columns['productPrice'])) {
							$productReportRow['productPrice'] = $o2p->getPrice();
						}
						
						$report[] = $productReportRow;
					}
				} else {
					$productReportRow = $reportRow;
					if (isset($columns['productId'])) {
						$productReportRow['productId'] = null;
					}
						
					if (isset($columns['productName'])) {
						$productReportRow['productName'] = null;
					}
					
					if (isset($columns['productCount'])) {
						$productReportRow['productCount'] = null;
					}
					
					if (isset($columns['productPrice'])) {
						$productReportRow['productPrice'] = null;
					}
					
					$report[] = $productReportRow;
				}
				
										
				
			}
			
			if (!$productsInReport) {
				$report[] = $reportRow;
			}
		}
		
		$this->_reportToFile($report);
	}
	
	/**
	 * Превращает массив отчета в файл нужного формата.
	 * 
	 * @param array $report
	 * @return void
	 */
	protected function _reportToFile($report)
	{
		$columns = CallCenterService::getInstance()->reportColumns;
		$columns = array_keys($columns);
		$columns = array_flip($columns);
		$nReport = array();
		foreach ($report as $reportRow) {
			$nReportRow = array();
			foreach ($reportRow as $key => $value) {
				$nReportRow[ $columns[$key] ] = $value;
			}
			
			ksort($nReportRow);
			$nReport[] = $nReportRow;
		}
		
		$string = '';
		$columns = $this->_getParam('report', array());
		foreach (CallCenterService::getInstance()->reportColumns as $key => $name) {
			if (isset($columns[$key])) {
				$string .= "\"$name\";";
			}
		}
		$string .= "\r\n";
		
		foreach ($nReport as $reportRow) {
			$string .= implode(';', $reportRow) . "\r\n";
		}
		
		$filename = date('Y_m_d_H_i_s');
		header("Content-type: application/vnd.ms-excel");
		header("Content-disposition: attachment; filename=$filename.csv");
		
		$string = iconv('utf-8', 'windows-1251', $string);
		echo $string;
		die();
	}
}
